package com.user.mediacoderdemo;

import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaCodec;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;



public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener, View.OnClickListener {

    private TextView video_address,m4a_address,duration_time;
    private TextView video_start_time,m4a_start_time,video_end_time,m4a_end_time;
    private SharedPreferences media_path;
    private SeekBar video_seekBar,m4a_seekBar, duration_seekBar;
    private Button btn_select_video,btn_select_m4a;
    private MediaExtractor videoExtractor,audioExtractor;
    private long m4a_duration,video_duration,start_video_time,start_m4a_time,new_video_duration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        media_path = getSharedPreferences("media_path", MODE_PRIVATE);
        video_address = (TextView) findViewById(R.id.video_address);
        m4a_address = (TextView) findViewById(R.id.m4a_address);
        video_start_time = (TextView) findViewById(R.id.video_start_time);
        m4a_start_time = (TextView) findViewById(R.id.m4a_start_time);
        video_end_time = (TextView) findViewById(R.id.video_end_time);
        m4a_end_time = (TextView) findViewById(R.id.m4a_end_time);
        duration_time = (TextView) findViewById(R.id.duration_time);

        video_seekBar = (SeekBar) findViewById(R.id.video_seekBar);
        duration_seekBar = (SeekBar) findViewById(R.id.duration_seekbar);
        m4a_seekBar = (SeekBar) findViewById(R.id.m4a_seekBar);
        btn_select_video = (Button) findViewById(R.id.btn_select_video);
        btn_select_m4a = (Button) findViewById(R.id.btn_select_m4a);
        video_seekBar.setOnSeekBarChangeListener(this);
        m4a_seekBar.setOnSeekBarChangeListener(this);
        duration_seekBar.setOnSeekBarChangeListener(this);
        btn_select_video.setOnClickListener(this);
        btn_select_m4a.setOnClickListener(this);


        showVideoText(media_path.getString("video_path", "视频地址"));
        showM4AText(media_path.getString("m4a_path", "音频地址"));
    }
    final   MediaOperateData operateData = new MediaOperateData();
    public void start(View view) {
        String media_path = this.media_path.getString("video_path", "");
//        String mp3_path = this.media_path.getString("mp3_path", "");
//        new Thread(new WorkThread(media_path,mp3_path)).start();

        operateData.duration = new_video_duration;
        operateData.output=new File(media_path).getParent() + File.separator + SystemClock.currentThreadTimeMillis() + "output.mp4";
        operateData.mediaExtractses = new ArrayList<>();
        //视频
        MediaOperateData.MediaExtracts video_mediaExtracts = new MediaOperateData.MediaExtracts();
        video_mediaExtracts.start_duration=start_video_time;
        video_mediaExtracts.end_duration=video_duration;
        video_mediaExtracts.extractor=videoExtractor;
        video_mediaExtracts.tag=MediaOperateData.MediaExtracts.VIDEO;
        operateData.mediaExtractses.add(video_mediaExtracts);
        //音频
        MediaOperateData.MediaExtracts audio_mediaExtracts = new MediaOperateData.MediaExtracts();
        audio_mediaExtracts.start_duration=start_m4a_time;
        audio_mediaExtracts.end_duration=m4a_duration;
        audio_mediaExtracts.tag=MediaOperateData.MediaExtracts.M4A;
        audio_mediaExtracts.extractor=audioExtractor;
        operateData.mediaExtractses.add(audio_mediaExtracts);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    MediaOperate.operateMedia(operateData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public void mp3Tom4a(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    MediaFormat mediaFormat =VideoInfoKit.getMediaFormat("video/", videoExtractor);
                    String mime = mediaFormat.getString(MediaFormat.KEY_MIME);
                    MediaCodec decoder=null;
                    if(!TextUtils.isEmpty(mime)){
                        decoder = MediaCodec.createDecoderByType(mime);
                        MediaOperate.MeidaFrameToImage(decoder,videoExtractor,mediaFormat);
                    }
//                    MediaOperate.MediaCodec(videoExtractor,mediaFormat);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public  void chooseType(String type,int resultcode) {
//        type  --> image/*,  audio/*  ,video/*
        Intent intent = new Intent();
        intent.setType(type); //选择视频 （mp4 3gp 是android支持的视频格式）
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, resultcode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 选取图片的返回值
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                String path = UriPathKit.getPath(MainActivity.this, uri);
                if (requestCode == REQUEST_VIDEO_CODE) {
                    showVideoText(path);
                    media_path.edit().putString("video_path", path).apply();
                } else if (requestCode == REQUEST_M4A_CODE){
                    showM4AText(path);
                    media_path.edit().putString("m4a_path", path).apply();
                }

            }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void showVideoText(String path) {
        Log.e("zoudong", "1----"+System.currentTimeMillis()+"path="+path);
        if (path.startsWith("/")) {
            video_address.setText(path);
            if (videoExtractor != null) {
                videoExtractor.release();
            }
            videoExtractor = VideoInfoKit.newIntance(path);
            MediaFormat mediaFormat = VideoInfoKit.getMediaFormat("video/", videoExtractor);
            if (mediaFormat != null) {
                video_duration = mediaFormat.getLong(MediaFormat.KEY_DURATION);
                video_end_time.setText(FormatTimeKit.getTime(video_duration / 1000l));
            }
            duration_seekBar.setProgress(100);
        }
        Log.e("zoudong", "2----"+System.currentTimeMillis());
    }

    private void showM4AText(String path) {
        if (path.startsWith("/")) {
            m4a_address.setText(path);
            if (audioExtractor != null) {
                audioExtractor.release();
            }
            audioExtractor = VideoInfoKit.newIntance(path);
            MediaFormat mediaFormat = VideoInfoKit.getMediaFormat("audio/", audioExtractor);
            if (mediaFormat != null) {
                m4a_duration = mediaFormat.getLong(MediaFormat.KEY_DURATION);
                m4a_end_time.setText(FormatTimeKit.getTime(m4a_duration /1000l));
            }
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        switch (seekBar.getId()) {
            case R.id.duration_seekbar:
                new_video_duration = video_duration * progress / 100l ;
                duration_time.setText(FormatTimeKit.getTime(new_video_duration/ 1000l));
                break;
            case R.id.video_seekBar:
                start_video_time = video_duration * progress / 100l;
                video_start_time.setText(FormatTimeKit.getTime(start_video_time / 1000l));
                break;
            case R.id.m4a_seekBar:
                start_m4a_time = m4a_duration * progress / 100l ;
                m4a_start_time.setText(FormatTimeKit.getTime(start_m4a_time/ 1000l));
                break;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MediaOperate.release(operateData);
    }

    private final String VIDEO = "video/*";
    private final String M4A = "audio/*";
    public static final int REQUEST_M4A_CODE = 2;
    public static final int REQUEST_VIDEO_CODE = 1;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_select_video:
                chooseType(VIDEO, REQUEST_VIDEO_CODE);
                break;
            case R.id.btn_select_m4a:
                chooseType(M4A, REQUEST_M4A_CODE);
                break;
        }
    }
}
